UP | HOME

Date: [2020-12-06 Sun]

Deftransform - SBCL

Transforms are something similar to Compiler macros. They are an implementation detail of SBCL implementation of Common Lisp.

For our example, we will implement a very basic transformation on the functions wat and string-wat, which are identical in form to our previous functions gen+ and string+.

Understand there are many more pieces of information and optimisation you can feed the SBCL compiler not covered here. And if anyone more experienced with SBCL internals wants to correct/extent anything regarding my impressions here, please comment and i'll be happy to update my answer:

First we tell the compiler about the existence and type signature of wat. We do this by calling defknown in the sb-c package and inform it that wat takes two parameters of any type: (T T) and that it returns a single value of any type: *

< Collapse code block> Expand code block
(sb-c:defknown wat (T T) *)

Then we define a simple transform using sb-c:deftransform, essentially saying when the two parameters fed to wat are strings, we transform the code into a call to string-wat.

< Collapse code block> Expand code block
(sb-c:deftransform wat ((x y) (string string) *)
  `(string-wat x y))

The forms of wat and string-wat for completeness:

< Collapse code block> Expand code block
(defun wat (x y)
  (if (and (numberp x)
           (numberp y))
      (+ x y)
      (concatenate 'string x y)))

(defun string-wat (x y)
  (declare (optimize (speed 3) (safety 0))
           (string x y))
  (concatenate 'string x y "watpow"))

And this time a demonstration in SBCL using bound variables but no explicit type declarations:

< Collapse code block> Expand code block
(let ((a (concatenate 'string "bo" "b"))
       (b (concatenate 'string "dole")))
   (wat a b))

And the returned string should be "bobdolewatpow".

Anoter useful comment was:

AFAIK reading the SBCL sources is the only way to learn how deftransform works. But before diving into SBCL sources checkout Paul Khuong's Starting to Hack on SBCL or at the very least The Python Compiler for CMU Common Lisp it links to to have an overview of how SBCL works.


References


Backlinks


You can send your feedback, queries here